package util

import (
	"fmt"
	"reflect"
	"regexp"
	"strings"

	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

// 判断是不是url格式
func IsURL(url string) bool {
	matched, err := regexp.MatchString(`(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`, url)

	if err != nil {
		return false
	}
	if !matched {
		return false
	}

	return true
}
func IsIPV4(IP string) bool {
	arr := strings.Split(IP, ".")
	if len(arr) != 4 {
		return false
	}
	for _, elem := range arr {
		if elem == "" {
			return false
		}
		if len(elem) > 1 && elem[0] == '0' {
			return false
		}
		num := 0
		for _, c := range elem {
			if c >= '0' && c <= '9' {
				num = num*10 + int(c-'0')
			} else {
				return false
			}
		}
		if num > 255 {
			return false
		}
	}
	return true
}

var validate *validator.Validate
var trans ut.Translator

func InitValidator() {
	uni := ut.New(zh.New())
	trans, _ = uni.GetTranslator("zh")
	validate = validator.New()
	validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
		name := fld.Tag.Get("label")
		return name
	})
	//验证器注册翻译器
	err := zh_translations.RegisterDefaultTranslations(validate, trans)
	if err != nil {
		fmt.Println(err)
	}
}

// ValidateStruct 验证结构体
func ValidateStruct(data interface{}, isAll bool) string {
	err := validate.Struct(data)
	strSli := make([]string, 0)
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			strSli = append(strSli, err.Translate(trans))
			if !isAll {
				break
			}
		}
	}
	return strings.Join(strSli, ",")
}
